<template>
  <div class="collection-detail">
    <!-- 头部信息 -->
    <div class="header">
      <div class="back" @click="goBack">
        <i class="kawaii-icon">🔙</i>
        <span>返回合集列表</span>
      </div>
      <div class="title-container">
        <h2 class="title">{{ collection.title }}</h2>
        <div class="count-container">
          <span class="count">{{ collection.videoCount }}个视频</span>
          <span class="count">{{ formattedDate }}</span>
        </div>
      </div>
    </div>

    <!-- 合集描述 -->
    <div class="description">
      <p>{{ collection.description }}</p>
    </div>

    <!-- 操作栏 -->
    <div class="actions">
      <div class="play-all" @click="playAll">
        <i class="kawaii-icon">💖</i>
        播放全部
      </div>
      <div class="sort-method">
        <button
          :class="['kawaii-filter-item', { active: sortType === 'newest' }]"
          @click="setSortType('newest')"
        >
          <i class="kawaii-icon">✨</i>
          最新发布
        </button>
        <button
          :class="[
            'kawaii-filter-item',
            { active: sortType === 'most_viewed' },
          ]"
          @click="setSortType('most_viewed')"
        >
          <i class="kawaii-icon">🔥</i>
          最多播放
        </button>
      </div>
      <div
        class="manage"
        v-if="isOwner"
        @click="showManageOptions = !showManageOptions"
      >
        <i class="kawaii-icon">⚙️</i>
        管理
      </div>
    </div>

    <!-- 视频列表 -->
    <div class="video-list">
      <VideoList :videos="sortedVideos" :loading="loading" />
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
      class="delete-dialog"
    >
      <div class="dialog-content">
        <div class="warning-text">确定要删除该合集吗？删除后不可恢复哦~</div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false" class="cancel-btn">
            取消
          </el-button>
          <el-button type="danger" @click="confirmDelete" class="confirm-btn">
            确定删除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, defineProps } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import VideoList from '@/views/front/videoList/VideoList.vue'

// 接收父组件传递的属性
const props = defineProps({
  userId: {
    type: [String, Number],
    required: true,
  },
  isOwner: {
    type: Boolean,
    default: false,
  },
  collectionId: {
    type: [String, Number],
    default: '',
  },
})

interface VideoData {
  id: number | string
  title: string
  thumbnail: string // 修改为与VideoList组件兼容的字段名
  duration: number
  viewCount: number // 修改为与VideoList组件兼容的字段名
  danmuCount: number // 修改为与VideoList组件兼容的字段名
  author: string
  createTime: string // 修改为与VideoList组件兼容的字段名
  tags?: string[]
}

interface CollectionData {
  id: number | string
  title: string
  description: string
  videoCount: number
  updateDate: string
  creatorId: number | string
}

// 路由相关
const route = useRoute()
const router = useRouter()

// 从路由参数或props中获取合集ID
const activeCollectionId = computed(() => {
  return props.collectionId || route.params.id
})

// 状态管理
const loading = ref(true)
const videos = ref<VideoData[]>([])
const collection = ref<CollectionData>({
  id: 0,
  title: '',
  description: '',
  videoCount: 0,
  updateDate: '',
  creatorId: 0,
})
const sortType = ref('newest')
const deleteDialogVisible = ref(false)
const showManageOptions = ref(false)

// 获取格式化后的日期
const formattedDate = computed(() => {
  return `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}-${String(new Date().getDate()).padStart(2, '0')} 更新`
})

// 排序后的视频
const sortedVideos = computed(() => {
  if (sortType.value === 'newest') {
    return [...videos.value].sort(
      (a, b) =>
        new Date(b.createTime).getTime() - new Date(a.createTime).getTime(),
    )
  } else {
    return [...videos.value].sort(
      (a, b) => Number(b.viewCount) - Number(a.viewCount),
    )
  }
})

// 返回合集列表
const goBack = () => {
  router.push(`/space/${props.userId}/collections`)
}

// 格式化数字
const formatCount = (count: number): string => {
  if (!count && count !== 0) return '0'
  if (count === 0) return '0'

  if (count < 10000) {
    return count.toString()
  } else if (count < 100000000) {
    return (count / 10000).toFixed(1) + '万'
  } else {
    return (count / 100000000).toFixed(1) + '亿'
  }
}

// 格式化时长
const formatDuration = (seconds: number): string => {
  if (!seconds) return '00:00'

  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 播放全部视频
const playAll = () => {
  if (videos.value.length > 0) {
    viewVideo(videos.value[0].id)
  } else {
    ElMessage.info('该合集暂无视频')
  }
}

// 设置排序方式
const setSortType = (type: string) => {
  sortType.value = type
}

// 查看视频
const viewVideo = (videoId: number | string) => {
  router.push(`/video/detail/${videoId}`)
}

// 处理更多菜单操作
const handleCommand = (command: string) => {
  if (command === 'edit') {
    // 编辑合集逻辑
    ElMessage.info('编辑合集功能待实现')
  } else if (command === 'delete') {
    deleteDialogVisible.value = true
  }
  showManageOptions.value = false
}

// 确认删除合集
const confirmDelete = async () => {
  try {
    // 模拟删除操作
    await new Promise((resolve) => setTimeout(resolve, 800))
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
    router.push(`/space/${props.userId}/collections`)
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟加载合集数据
const fetchCollectionData = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 800))

    // 模拟合集数据
    collection.value = {
      id: activeCollectionId.value,
      title: '二次元精选动画合集',
      description:
        '这是一个精心挑选的二次元动画合集，包含了各种经典片段和热门作品。无论你是动漫新手还是老司机，这里都有适合你的内容！',
      videoCount: 8,
      updateDate: '2024-08-20',
      creatorId: props.userId,
    }

    // 获取视频列表
    await fetchVideoList()
  } catch (error) {
    console.error('获取合集数据失败:', error)
    ElMessage.error('获取合集数据失败')
  }
}

// 获取视频列表
const fetchVideoList = async () => {
  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 600))

    // 模拟视频数据 - 二次元主题，适配VideoList组件的数据结构
    const mockVideos: VideoData[] = [
      {
        id: 1001,
        title: '【治愈向AMV】当夏天相遇，最美的风景藏在记忆里',
        thumbnail: '/src/assets/anime/images/banner10.png',
        duration: 272,
        viewCount: 217000,
        danmuCount: 3560,
        author: '二次元领域',
        createTime: '2023-08-11',
        tags: ['AMV', '治愈'],
      },
      {
        id: 1002,
        title: '【新海诚】声之形×你的名字 | 两部催泪神作的完美结合',
        thumbnail: '/src/assets/anime/images/banner11.png',
        duration: 221,
        viewCount: 106000,
        danmuCount: 1890,
        author: '动画研究社',
        createTime: '2023-07-23',
        tags: ['新海诚', '催泪'],
      },
      {
        id: 1003,
        title: '【宫崎骏】龙猫与千与千寻的奇妙冒险',
        thumbnail: '/src/assets/anime/images/banner12.png',
        duration: 187,
        viewCount: 89500,
        danmuCount: 1245,
        author: '宫崎骏作品赏析',
        createTime: '2023-06-15',
        tags: ['宫崎骏', '经典动画'],
      },
      {
        id: 1004,
        title: '【热血燃向】进击的巨人最终季 | 艾伦的自由之路',
        thumbnail: '/src/assets/anime/images/banner13.png',
        duration: 314,
        viewCount: 321000,
        danmuCount: 5670,
        author: '巨人考察团',
        createTime: '2023-05-28',
        tags: ['进击的巨人', '热血'],
      },
      {
        id: 1005,
        title: '【催泪向】我想吃掉你的胰脏 | 生命的意义与遗憾',
        thumbnail: '/src/assets/anime/images/banner14.png',
        duration: 256,
        viewCount: 198700,
        danmuCount: 4320,
        author: '动漫研究社',
        createTime: '2023-04-17',
        tags: ['催泪', '电影'],
      },
      {
        id: 1006,
        title: '【名场面】鬼灭之刃 | 炭治郎水之呼吸·拾壹之型',
        thumbnail: '/src/assets/anime/images/banner1.png',
        duration: 175,
        viewCount: 437900,
        danmuCount: 7820,
        author: '翻译君字幕组',
        createTime: '2023-03-22',
        tags: ['鬼灭之刃', '战斗'],
      },
      {
        id: 1007,
        title: '【经典回顾】火影忍者 | 鸣人VS佩恩完整战役',
        thumbnail: '/src/assets/anime/images/banner2.png',
        duration: 342,
        viewCount: 527100,
        danmuCount: 8950,
        author: '漫评家小佐',
        createTime: '2023-02-09',
        tags: ['火影忍者', '经典战斗'],
      },
      {
        id: 1008,
        title: '【萌系】间谍过家家 | 阿尼亚的可爱时刻合集',
        thumbnail: '/src/assets/anime/images/banner3.png',
        duration: 198,
        viewCount: 276500,
        danmuCount: 5430,
        author: '萌系画师协会',
        createTime: '2023-01-18',
        tags: ['间谍过家家', '萌系'],
      },
    ]

    videos.value = mockVideos
  } catch (error) {
    console.error('获取视频列表失败:', error)
    ElMessage.error('获取视频列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchCollectionData()
})
</script>

<style lang="scss" scoped>
.collection-detail {
  position: relative;
  min-height: 100vh;
  background: linear-gradient(135deg, #ffebf0 0%, #ffe0e8 100%);
  padding: 20px;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: radial-gradient(
        circle at 10% 20%,
        rgba(255, 182, 193, 0.1) 0%,
        transparent 20%
      ),
      radial-gradient(
        circle at 80% 40%,
        rgba(255, 105, 180, 0.1) 0%,
        transparent 20%
      ),
      radial-gradient(
        circle at 30% 70%,
        rgba(255, 192, 203, 0.1) 0%,
        transparent 20%
      ),
      radial-gradient(
        circle at 90% 90%,
        rgba(255, 182, 193, 0.1) 0%,
        transparent 20%
      );
    z-index: 0;
  }

  // 漂浮的心形装饰
  .heart {
    position: absolute;
    background-color: rgba(255, 182, 193, 0.3);
    border-radius: 50%;
    z-index: 0;

    &::before,
    &::after {
      content: '';
      position: absolute;
      background-color: rgba(255, 182, 193, 0.3);
      border-radius: 50%;
    }

    &::before {
      width: 100%;
      height: 100%;
      top: -50%;
      left: 0;
    }

    &::after {
      width: 100%;
      height: 100%;
      top: 0;
      left: 50%;
    }

    &:nth-child(1) {
      width: 40px;
      height: 40px;
      top: 10%;
      left: 5%;
      animation: float 20s infinite ease-in-out;
    }

    &:nth-child(2) {
      width: 30px;
      height: 30px;
      top: 15%;
      right: 10%;
      animation: float 25s infinite ease-in-out;
      animation-delay: 3s;
    }

    &:nth-child(3) {
      width: 50px;
      height: 50px;
      bottom: 20%;
      left: 15%;
      animation: float 18s infinite ease-in-out;
      animation-delay: 6s;
    }

    &:nth-child(4) {
      width: 25px;
      height: 25px;
      bottom: 30%;
      right: 20%;
      animation: float 22s infinite ease-in-out;
      animation-delay: 4s;
    }
  }

  @keyframes float {
    0%,
    100% {
      transform: translateY(0) rotate(0deg);
    }

    25% {
      transform: translateY(-20px) rotate(5deg);
    }

    50% {
      transform: translateY(0) rotate(0deg);
    }

    75% {
      transform: translateY(20px) rotate(-5deg);
    }
  }

  .content {
    position: relative;
    z-index: 1;
    background-color: rgba(255, 255, 255, 0.85);
    border-radius: 20px;
    padding: 25px;
    box-shadow: 0 10px 30px rgba(255, 105, 180, 0.15);
    backdrop-filter: blur(10px);
    border: 2px solid rgba(255, 182, 193, 0.3);

    .header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .back {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        border-radius: 12px;
        background-color: #ffebf0;
        color: #ff5c8d;
        font-size: 18px;
        margin-right: 15px;
        cursor: pointer;
        transition: all 0.3s;
        border: 1px solid rgba(255, 182, 193, 0.5);

        &:hover {
          background-color: #ff80ab;
          color: #fff;
          transform: translateY(-2px);
          box-shadow: 0 5px 15px rgba(255, 105, 180, 0.2);
        }
      }

      .title {
        font-size: 22px;
        font-weight: 600;
        color: #ff5c8d;
        display: flex;
        align-items: center;

        .count {
          margin-left: 10px;
          font-size: 14px;
          font-weight: 500;
          color: #ff80ab;
          background-color: #ffebf0;
          padding: 4px 10px;
          border-radius: 100px;
          border: 1px solid rgba(255, 182, 193, 0.5);
        }
      }
    }

    .description {
      font-size: 15px;
      color: #ff80ab;
      margin-bottom: 25px;
      padding: 12px 18px;
      background-color: #fff5f8;
      border-radius: 12px;
      border-left: 4px solid #ff80ab;
    }

    .actions {
      display: flex;
      align-items: center;
      gap: 15px;
      margin-bottom: 25px;

      .play-all {
        display: flex;
        align-items: center;
        gap: 8px;
        background-color: #ff80ab;
        color: #fff;
        padding: 10px 20px;
        border-radius: 10px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s;
        border: none;

        &:hover {
          background-color: #ff5c8d;
          transform: translateY(-2px);
          box-shadow: 0 5px 15px rgba(255, 105, 180, 0.2);
        }
      }

      .sort-method {
        display: flex;
        align-items: center;
        gap: 8px;
        background-color: #fff5f8;
        color: #ff80ab;
        padding: 10px 20px;
        border-radius: 10px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s;
        border: 1px solid rgba(255, 182, 193, 0.5);

        &:hover {
          background-color: #ffebf0;
          transform: translateY(-2px);
        }
      }

      .manage {
        margin-left: auto;
        display: flex;
        align-items: center;
        gap: 8px;
        background-color: #fff5f8;
        color: #ff80ab;
        padding: 10px 20px;
        border-radius: 10px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s;
        border: 1px dashed rgba(255, 182, 193, 0.7);

        &:hover {
          background-color: #ffebf0;
          transform: translateY(-2px);
        }
      }
    }

    .video-list {
      border-radius: 15px;
      background-color: #fff5f8;
      padding: 20px;
      border: 1px solid rgba(255, 182, 193, 0.3);

      .video-item {
        background-color: #fff;
        border-radius: 12px;
        margin-bottom: 15px;
        overflow: hidden;
        transition: all 0.3s;
        border: 1px solid rgba(255, 182, 193, 0.2);

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 8px 20px rgba(255, 105, 180, 0.1);
          border-color: rgba(255, 182, 193, 0.6);
        }

        .video-info {
          display: flex;
          padding: 15px;

          .cover {
            width: 180px;
            height: 110px;
            border-radius: 8px;
            overflow: hidden;
            position: relative;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            .duration {
              position: absolute;
              bottom: 5px;
              right: 5px;
              background-color: rgba(0, 0, 0, 0.7);
              color: #fff;
              font-size: 12px;
              padding: 2px 6px;
              border-radius: 4px;
            }
          }

          .details {
            flex: 1;
            margin-left: 15px;

            .video-title {
              font-size: 16px;
              font-weight: 600;
              color: #ff5c8d;
              margin-bottom: 8px;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }

            .uploader {
              display: flex;
              align-items: center;
              font-size: 14px;
              color: #ff80ab;
              margin-bottom: 8px;

              .avatar {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                margin-right: 8px;
              }
            }

            .stats {
              display: flex;
              align-items: center;
              gap: 15px;
              font-size: 13px;
              color: #ff80ab;

              .stat {
                display: flex;
                align-items: center;
                gap: 5px;
              }
            }
          }

          .actions {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-left: 10px;

            .action-btn {
              width: 36px;
              height: 36px;
              border-radius: 10px;
              display: flex;
              align-items: center;
              justify-content: center;
              background-color: #fff5f8;
              color: #ff80ab;
              transition: all 0.3s;
              cursor: pointer;

              &:hover {
                background-color: #ff80ab;
                color: #fff;
                transform: translateY(-2px);
              }
            }
          }
        }
      }
    }
  }
}

.delete-dialog {
  .el-dialog__header {
    background-color: #ffebf0;
  }

  .el-dialog__title {
    color: #ff5c8d;
  }

  .dialog-content {
    padding: 20px 0;

    .warning-text {
      color: #ff5c8d;
      font-weight: 500;
    }
  }

  .dialog-footer {
    .cancel-btn {
      border-color: #ff80ab;
      color: #ff80ab;

      &:hover {
        background-color: #fff5f8;
        color: #ff5c8d;
      }
    }

    .confirm-btn {
      background-color: #ff5c8d;
      border-color: #ff5c8d;

      &:hover {
        background-color: #ff3d7f;
        border-color: #ff3d7f;
      }
    }
  }
}
</style>
